﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace SysMonitor
{
    public class Export
    {
        #region ToExcel

        public static bool Export2Excel(ListView listView,string strFilePath)
        {
            int rowNum = listView.Items.Count;
            int columnNum = listView.Items[0].SubItems.Count;
            int rowIndex = 1;
            int columnIndex = 0;
            if (rowNum == 0 || string.IsNullOrEmpty(strFilePath))
            {
                return false;
            }
            if (rowNum > 0)
            {
                try
                {
                    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    if (xlApp == null)
                    {
                        MessageBox.Show("无法创建excel对象，可能您的系统没有安装excel");
                        return false;
                    }
                    xlApp.DefaultFilePath = "";
                    xlApp.DisplayAlerts = true;
                    xlApp.SheetsInNewWorkbook = 1;
                    Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
                    //将ListView的列名导入Excel表第一行
                    foreach (ColumnHeader dc in listView.Columns)
                    {
                        columnIndex++;
                        xlApp.Cells[rowIndex, columnIndex] = dc.Text;
                    }
                    //将ListView中的数据导入Excel中
                    for (int i = 0; i < rowNum; i++)
                    {
                        rowIndex++;
                        columnIndex = 0;
                        for (int j = 0; j < columnNum; j++)
                        {
                            columnIndex++;
                            //注意这个在导出的时候加了“\t” 的目的就是避免导出的数据显示为科学计数法。可以放在每行的首尾。
                            xlApp.Cells[rowIndex, columnIndex] = Convert.ToString(listView.Items[i].SubItems[j].Text) + "\t";
                        }
                    }
                    //例外需要说明的是用strFileName,Excel.XlFileFormat.xlExcel9795保存方式时 当你的Excel版本不是95、97 而是2003、2007 时导出的时候会报一个错误：异常来自 HRESULT:0x800A03EC。 解决办法就是换成strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal。
                    xlBook.SaveAs(strFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    xlBook = null;
                    xlApp = null;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return false;
                }
            }
            return true;
        }

        public static bool Export2Excel(ListView listView, ListView.SelectedListViewItemCollection SelectedItems, string strFilePath)
        {
            int rowNum = SelectedItems.Count;;
            int columnNum = listView.Columns.Count;
            int rowIndex = 1;
            int columnIndex = 0;
            if (rowNum == 0 || string.IsNullOrEmpty(strFilePath))
            {
                return false;
            }
            if (rowNum > 0)
            {

                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                if (xlApp == null)
                {
                    MessageBox.Show("无法创建excel对象，可能您的系统没有安装excel");
                    return false;
                }
                xlApp.DefaultFilePath = "";
                xlApp.DisplayAlerts = true;
                xlApp.SheetsInNewWorkbook = 1;
                Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
                //将ListView的列名导入Excel表第一行
                foreach (ColumnHeader dc in listView.Columns)
                {
                    columnIndex++;
                    xlApp.Cells[rowIndex, columnIndex] = dc.Text;
                }
                //将ListView中选中的数据导入Excel中
                foreach (ListViewItem Item in SelectedItems)
                {
                    rowIndex++;
                    columnIndex = 0;
                    for (int j = 0; j < columnNum; j++)
                    {
                        columnIndex++;
                        xlApp.Cells[rowIndex, columnIndex] = Convert.ToString(Item.SubItems[j].Text) + "\t";
                    }
                }
                //例外需要说明的是用strFileName,Excel.XlFileFormat.xlExcel9795保存方式时 当你的Excel版本不是95、97 而是2003、2007 时导出的时候会报一个错误：异常来自 HRESULT:0x800A03EC。 解决办法就是换成strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal。
                xlBook.SaveAs(strFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                xlBook = null;
                xlApp = null;
            }
            return true;
        }

        public static bool Export2Excel(List<string> cols, List<string> vals, string strFilePath)
        {
            int rowNum = vals.Count;
            int columnNum = cols.Count;
            int rowIndex = 1;
            int columnIndex = 0;
            if (rowNum == 0 || string.IsNullOrEmpty(strFilePath))
            {
                return false;
            }
            if (rowNum > 0)
            {
                if (File.Exists(strFilePath))
                {
                    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    if (xlApp == null)
                    {
                        MessageBox.Show("无法创建excel对象，可能您的系统没有安装excel");
                        return false;
                    }
                    Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Open(strFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Sheets[1];
                    rowIndex = xlSheet.UsedRange.Rows.Count + 1;
                    if (rowIndex == 1)
                    {
                        foreach (string col in cols)
                        {
                            columnIndex++;
                            xlApp.Cells[rowIndex, columnIndex] = col;
                        }
                    }
                    foreach (string val in vals)
                    {
                        rowIndex++;
                        columnIndex = 0;
                        for (int j = 0; j < columnNum; j++)
                        {
                            columnIndex++;
                            //注意这个在导出的时候加了“\t” 的目的就是避免导出的数据显示为科学计数法。可以放在每行的首尾。
                            xlApp.Cells[rowIndex, columnIndex] = val + "\t";
                        }
                    }
                    xlBook.Save();
                    xlSheet = null;
                    xlBook = null;
                    xlApp = null;
                }
                else
                {
                    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    xlApp.DefaultFilePath = "";
                    xlApp.DisplayAlerts = true;
                    xlApp.SheetsInNewWorkbook = 1;
                    Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
                    //将列名导入Excel表第一行
                    foreach (string col in cols)
                    {
                        columnIndex++;
                        xlApp.Cells[rowIndex, columnIndex] = col;
                    }
                    xlBook.SaveAs(strFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    //将数据导入Excel中
                    foreach (string val in vals)
                    {
                        rowIndex++;
                        columnIndex = 0;
                        for (int j = 0; j < columnNum; j++)
                        {
                            columnIndex++;
                            //注意这个在导出的时候加了“\t” 的目的就是避免导出的数据显示为科学计数法。可以放在每行的首尾。
                            xlApp.Cells[rowIndex, columnIndex] = val + "\t";
                        }
                    }
                    //例外需要说明的是用strFileName,Excel.XlFileFormat.xlExcel9795保存方式时 当你的Excel版本不是95、97 而是2003、2007 时导出的时候会报一个错误：异常来自 HRESULT:0x800A03EC。 解决办法就是换成strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal。
                    //xlBook.SaveAs(strFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    xlBook.Save();
                    xlBook = null;
                    xlApp = null;
                }
            }
            return true;
        }

        #endregion

        #region ToCSV

        public static bool Export2CSV(ListView listView, string strFilePath)
        {
            FileStream fs = null;
            StreamWriter text = null;
            string RecordLine = "";

            try
            {
                fs = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.Read);
                text = new StreamWriter(fs, Encoding.Default);
                for (int i = 0; i < listView.Columns.Count; i++)
                {
                    RecordLine += "\"" + listView.Columns[i].Text + "\",";
                }
                text.WriteLine(RecordLine.Remove(RecordLine.Length - 1));
                text.Flush();

                for (int i = 0; i < listView.Items.Count; i++)
                {
                    RecordLine = "";
                    for (int j = 0; j < listView.Columns.Count; j++)
                    {
                        RecordLine += "\"" + listView.Items[i].SubItems[j].Text + "\",";
                    }
                    text.WriteLine(RecordLine.Remove(RecordLine.Length - 1));
                    text.Flush();
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                fs.Dispose();
            }
            return true;
        }

        public static bool Export2CSV(ListView listView, ListView.SelectedListViewItemCollection SelectedItems, string strFilePath)
        {
            FileStream fs = null;
            StreamWriter text = null;
            string RecordLine = "";

            try
            {
                fs = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.Read);
                text = new StreamWriter(fs, Encoding.Default);
                for (int i = 0; i < listView.Columns.Count; i++)
                {
                    RecordLine += "\"" + listView.Columns[i].Text + "\",";
                }
                text.WriteLine(RecordLine.Remove(RecordLine.Length - 1));
                text.Flush();

                foreach (ListViewItem Item in SelectedItems)
                {
                    RecordLine = "";
                    for (int j = 0; j < listView.Columns.Count; j++)
                    {
                        RecordLine += "\"" + Item.SubItems[j].Text + "\",";
                    }
                    text.WriteLine(RecordLine.Remove(RecordLine.Length - 1));
                    text.Flush();
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                fs.Dispose();
            }
            return true;
        }

        public static bool Export2CSV(List<string> cols, List<string> vals, string strFilePath)
        {
            bool isfile = false;
            FileStream fs = null;
            StreamWriter text = null;
            string RecordLine = "";

            try
            {
                if (File.Exists(strFilePath)) isfile = true;
                fs = new FileStream(strFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
                text = new StreamWriter(fs, Encoding.Default);
                if (!isfile)
                {
                    foreach (string col in cols)
                    {
                        RecordLine += "\"" + col + "\",";
                    }
                    text.WriteLine(RecordLine.Remove(RecordLine.Length - 1));
                    text.Flush();
                }

                RecordLine = "";
                foreach (string val in vals)
                {
                    RecordLine += "\"" + val + "\",";
                }
                text.WriteLine(RecordLine.Remove(RecordLine.Length - 1));
                text.Flush();
            }
            catch
            {
                return false;
            }
            finally
            {
                fs.Dispose();
            }
            return true;
        }

        #endregion

        #region ToTxt

        public static bool Export2Txt(ListView listView, string strFilePath)
        {
            FileStream fs = null;
            StreamWriter text = null;
            string RecordLine = "";

            try
            {
                fs = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.Read);
                text = new StreamWriter(fs, Encoding.Default);
                for (int i = 0; i < listView.Columns.Count; i++)
                {
                    RecordLine += listView.Columns[i].Text + "\t";
                }
                text.WriteLine(RecordLine);
                text.Flush();

                for (int i = 0; i < listView.Items.Count; i++)
                {
                    RecordLine = "";
                    for (int j = 0; j < listView.Columns.Count; j++)
                    {
                        RecordLine += listView.Items[i].SubItems[j].Text + "\t";
                    }
                    text.WriteLine(RecordLine);
                    text.Flush();
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                fs.Close();
            }
            return true;
        }

        public static bool Export2Txt(ListView listView, ListView.SelectedListViewItemCollection SelectedItems, string strFilePath)
        {
            FileStream fs = null;
            StreamWriter text = null;
            string RecordLine = "";

            try
            {
                fs = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.Read);
                text = new StreamWriter(fs, Encoding.Default);
                for (int i = 0; i < listView.Columns.Count; i++)
                {
                    RecordLine += listView.Columns[i].Text + "\t";
                }
                text.WriteLine(RecordLine);
                text.Flush();

                foreach (ListViewItem Item in SelectedItems)
                {
                    RecordLine = "";
                    for (int j = 0; j < listView.Columns.Count; j++)
                    {
                        RecordLine += Item.SubItems[j].Text + "\t";
                    }
                    text.WriteLine(RecordLine);
                    text.Flush();
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                fs.Dispose();
            }
            return true;
        }

        public static bool Export2Txt(List<string> cols, List<string> vals, string strFilePath)
        {
            bool isfile = false;
            FileStream fs = null;
            StreamWriter text = null;
            string RecordLine = "";

            try
            {
                if (File.Exists(strFilePath)) isfile = true;
                fs = new FileStream(strFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
                text = new StreamWriter(fs, Encoding.Default);
                if (!isfile)
                {
                    foreach (string col in cols)
                    {
                        RecordLine += col + "\t";
                    }
                    text.WriteLine(RecordLine);
                    text.Flush();
                }

                RecordLine = "";
                foreach (string val in vals)
                {
                    RecordLine += val + "\t";
                }
                text.WriteLine(RecordLine);
                text.Flush();
            }
            catch
            {
                return false;
            }
            finally
            {
                fs.Dispose();
            }
            return true;
        }

        #endregion
    }
}
